<!--收费单详情-->
<template>
  <div class="generate-bill-info ne-relative"
       v-loading="loading"
       element-loading-customClass="ne-loading"
       element-loading-background="rgba(255, 255, 255, 0.6)"
  >
    <div  style="height: 100%;overflow-y: auto;">
      <el-form
          ref="TcForm2"
          label-position="left"
          label-width="1rem"
          :model="Form"
      >
        <el-row>
          <tc-form2 :form="Form"></tc-form2>
          <h2 class="ne-title-v2">一次性费用详单</h2>
          <DicTable
              height="100%"
              stripe
              max-height="600"
              ref="GQTable"
              border
              header-row-class-name="header-row-class"
              :columnData="GQtbs.tableColumns"
              :tableData="GQtbs.tableData"
              :loading="GQtbs.tableLoading"
              :pager="false"
          >
            <template #radioMat="{ row }">
              <div class="flex">
                <el-input v-model="row.radioMat" placeholder=""></el-input>
                <p style="margin-left: .05rem">%</p>
              </div>
            </template>
            <template #radioEng="{ row }">
              <div class="flex">
                <el-input v-model="row.radioEng" placeholder=""></el-input>
                <p style="margin-left: .05rem">%</p>
              </div>
            </template>
            <template #radioDev="{ row }">
              <div class="flex">
                <el-input v-model="row.radioDev" placeholder=""></el-input>
                <p style="margin-left: .05rem">%</p>
              </div>
            </template>
          </DicTable>
          <tc-form2 class="mar-20" :form="FormB"></tc-form2>
        </el-row>
        <el-row class="fixed">
          <el-col :span="24" class="ne-line-r flex flex-center">
            <div v-if="showBtn2">
              <el-button type="primary" size="medium" @click="openDialog('选择核实收费人',false)">确定</el-button>
              <el-button type="primary" size="medium">返回</el-button>
            </div>
            <div v-if="showBtn1">
              <el-button type="primary" size="medium">重新报价</el-button>
              <el-button type="primary" size="medium" @click="openDialog('送审核收费单',true)">送审核</el-button>
            </div>
            <el-button type="primary" size="medium" @click="modidyRate">修改优惠率</el-button>
            <el-button v-if="showBtn1||showBtn2" type="primary" size="medium" @click="save">保存</el-button>
            <el-button type="primary" size="medium" @click="verifyGenerateBill">核实资费</el-button>
            <el-button type="primary" size="medium">输出Excel</el-button>
            <el-button size="medium" @click="closeFun">关闭</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <el-dialog append-to-body :close-on-click-modal='false' :title="dialogTitle" v-if="AuditdialogVisible" :visible.sync="AuditdialogVisible"
               v-loading="loading2"
               element-loading-customClass="ne-loading"
               element-loading-background="rgba(255, 255, 255, 0.6)"
    >
        <el-form v-if="audit" :model="audName">
          <el-form-item :label="audName.cName" label-width="1rem">
            <el-select v-model="audName.cValue" placeholder="请选择">
              <el-option
                  v-for="(item,index) in audName.opt"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-form v-else :model="gryBillAudName">
          <el-form-item :label="gryBillAudName.cName" label-width="1rem">
            <el-select v-model="gryBillAudName.cValue" placeholder="请选择">
              <el-option
                  v-for="(item,index) in gryBillAudName.opt"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="send">发送</el-button>
          <el-button @click="AuditdialogVisible = false">取 消</el-button>
        </div>
    </el-dialog>
  </div>
</template>
<script>
import TcForm2 from "@/components/public/TcForm2";
import DicTable from "@/components/public/DicTable";
import CustOrderService from "@/api/order/CustOrderService";
import { mapState } from "vuex";
export default {
  name: "GenerateBillInfo",
  data() {
    return {
      loading:false,
      loading2:false,
      audit: true,
      dialogTitle:'',
      audName:{
        type:'select',
        cName:'审核人',
        cValue:'',
        required:true,
        opt:[],
        show:true,
        span:24,
      },
      gryBillAudName:{
        type:'select',
        cName:'审核人',
        cValue:'',
        required:true,
        opt:[],
        show:true,
        span:24,
      },
      Form:{
        "custSoNumber": {
          type: 'Ipt',
          name: '流水号',
          readonly: true,
          value: "",
          id: "custSoNumber",
          show: true,
          span: 6
        },
        "custName": {
          type: 'Ipt',
          name: '客户名称',
          readonly: true,
          value: "",
          id: "custName",
          show: true,
          span: 6
        },
        "contactCd": {
          type: 'Ipt',
          name: '合同编码',
          readonly: true,
          value: "",
          id: "contactCd",
          show: true,
          span: 6,
          marginRight:'25%'
        },
        "custNumber": {
          type: 'Ipt',
          name: '客户编码',
          readonly: true,
          value: "",
          id: "custNumber",
          show: true,
          span: 6
        },
        "payType": {
          type: 'Ipt',
          name: '收费方式',
          readonly: true,
          value: "",
          id: "payType",
          show: true,
          span: 6,
          marginRight:'50%'
        },
        "allRmb": {
          type: 'Ipt',
          name: '合计',
          readonly: true,
          value: "￥0",
          id: "priceRmb",
          show: true,
          span: 6
        },
        "rmbBig": {
          type: 'Ipt',
          name: '大写(元)',
          readonly: true,
          value: "零元",
          id: "rmbBig",
          show: true,
          span: 6
        },
        "rmbSmall": {
          type: 'Ipt',
          name: '小计',
          readonly: true,
          value: "￥0",
          id: "priceRmb",
          show: true,
          span: 6,
          marginRight:'25%'
        }
      },
      FormB:{
        "rmbxj": {
          type: 'Ipt',
          name: '人民币小计',
          readonly: true,
          value: "￥0",
          id: "priceRmb",
          show: true,
          span: 6,
          marginRight:'75%'
        },
        "moneySum": {
          type: 'Ipt',
          name: '合计',
          readonly: true,
          value: "￥0",
          id: "priceRmb",
          show: true,
          span: 6,
          marginRight:'75%'
        },
        "billComment": {
          type: 'textarea',
          name: '备注',
          value: "",
          id: "billComment",
          show: true,
          span: 12,
          marginRight:'50%'
        },
      },
      GQtbs:{
        tableColumns: [
          { field: "regionRange", title: "电路名称"},
          { field: "nodeName", title: "单位"},
          { field: "offerName", title: "业务种类"},
          { field: "inputType", title: "接入电路类型"},
          { field: "speed", title: "速率"},
          { field: "custOrderType", title: "类型"},
          { field: "moneyRmbMat", title: "工料费"},
          { field: "moneyRmbTest", title: "调测费"},
          { field: "moneyRmbPro", title: "手续费"},
          { field: "subtotal", title: "小计"},
          { slotName: "radioMat", title: "装机优惠率(%)"},
          { field: "moneyRmbEng", title: "工程费"},
          { slotName: "radioEng", title: "工程费优惠率(%)"},
          { field: "moneyRmbDev", title: "设备费"},
          { slotName: "radioDev", title: "设备费优惠率(%)"},
          { field: "receivables", title: "应收款"},
        ],
        tableData:  [],
        tableLoading: false,
      },
      showBtn1:true,
      showBtn2:true,
      taskId:null,
      AuditdialogVisible:false
    }
  },
  props: {
    rowInfo: {
      type: Object
    },
    allInfo: {
      type: Object
    }
  },
  mounted() {

  },
  computed:{
    ...mapState('user',['user'])
  },
  created() {
    this.getAudUserList();
    this.getHsAudUserList();
    this.getDetail();
  },
  components: {TcForm2,DicTable},
  methods: {
    openDialog(title,audit){
      this.AuditdialogVisible = true;
      this.dialogTitle = title;
      this.audit = audit;
    },
    send(){
      if(this.audit){
        this.sendAuditSave();
      }else{
        this.saveAudit();
      }
    },
    async verifyGenerateBill(){
      this.loading = true;
      let{custOrderId,orderAuditId,custSoNumber,offerType,prodOfferId,custId} = this.allInfo,
          {acctItemListId} = this.rowInfo;
      let comment = this.FormB.billComment.value,
          oneOrmany='many',
          taskId = this.taskId,
          userId = this.user.staffId,
          orderAudFlag=1;
      taskId = 'TACHE00070003';
      const result = await CustOrderService.verifyGenerateBill({orderAuditId,acctItemListId,taskId,orderAudFlag,userId,oneOrmany,custOrderId,custSoNumber,offerType,prodOfferId,custId,comment});
      this.loading = false;
      if(result.meta.resultCode == 0){
        this.$message({
          type: 'success',
          message: '保存成功!'
        });
        this.getDetail();
      }else{
        this.$message({
          showClose: true,
          message: result.meta.resultMsg,
          type: 'error'
        });
      }
    },
    async saveAudit(){
      this.loading2 = true;
      let{custOrderId,orderAuditId,custSoNumber,offerType,prodOfferId,custId} = this.allInfo,
          {acctItemListId} = this.rowInfo;
      let comment = this.FormB.billComment.value,
          oneOrmany='many',
          taskId = this.taskId,
          userId = this.user.staffId,
          orderAudFlag=1,
          audUserId = this.gryBillAudName.cValue;
      const result = await CustOrderService.saveAuditGenerateBill({audUserId,orderAuditId,acctItemListId,taskId,orderAudFlag,userId,oneOrmany,custOrderId,custSoNumber,offerType,prodOfferId,custId,comment});
      this.loading2 = false;
      if(result.meta.resultCode == 0){
        this.$message({
          type: 'success',
          message: '保存成功!'
        });
        this.AuditdialogVisible = false;
        this.getDetail();
      }else{
        this.$message({
          showClose: true,
          message: result.meta.resultMsg,
          type: 'error'
        });
      }
    },
    async sendAuditSave(){
      this.loading2 = true;
      let{custOrderId,custSoNumber,offerType,orderAuditId,custId} = this.allInfo;
      let audUserId = this.audName.cValue,
          audUserName = this.getLabel(this.audName.opt,audUserId),
          oneOrmany = 'many',
          taskId = this.taskId,
          {acctItemListId} = this.rowInfo,
          userId = this.user.staffId;
      const result = await CustOrderService.sendAuditGenerateBill({acctItemListId,taskId,oneOrmany,userId,custOrderId,custSoNumber,offerType,orderAuditId,custId,audUserId,audUserName,});
      this.loading2 = false;
      if(result.meta.resultCode == 0){
        this.$message({
          type: 'success',
          message: '保存成功!'
        });
        this.AuditdialogVisible=false;
        this.getDetail();
      }else{
        this.$message({
          showClose: true,
          message: result.meta.resultMsg,
          type: 'error'
        });
      }
    },
    async getAudUserList(){
      let {custId,custOrderId} = this.allInfo,
          {acctItemListId} = this.rowInfo;
      const result = await CustOrderService.gryBillAudUserList({custId,custOrderId,acctItemListId});
      this.audName.opt = {...result.meta};
    },
    async getHsAudUserList(){
      let {custId,custOrderId} = this.allInfo,
          {acctItemListId} = this.rowInfo;
      const result = await CustOrderService.gryBillAudUserList({custId,custOrderId,acctItemListId});
      this.gryBillAudName.opt = {...result.meta};
    },
    async getDetail(){
      this.loading = true;
      // acctItemListId 非必填字段，列表中点击进入需要填
      let{custOrderId,custSoNumber,offerType,prodOfferId,custId} = this.allInfo,
          {acctItemListId} = this.rowInfo,
          params = {acctItemListId,custOrderId,custSoNumber,custId,...{prodType:offerType,offerId:prodOfferId}};
      const result = await CustOrderService.qryGenerateBillDetail(params),
            res = result.meta;
      this.loading = false;
      if(res.resultCode == '0'){
        if(res.hasOwnProperty('orderBandInterBillUppers')){
          this.GQtbs.tableData = this.tableDataInit(res.orderBandInterBillLowers);
          // this.GQtbs.tableData = result.meta.orderBillLowerParts;
          for(var key in res.orderBandInterBillUppers[0]){
            let value = res.orderBandInterBillUppers[0][key];
            for(var key2 in this.Form){
              if(this.Form[key2].id == key){
                this.Form[key2].value = value;
              }
            }
            for(var key2 in this.FormB){
              if(this.FormB[key2].id == key){
                this.FormB[key2].value = value;
              }
            }
          };
          if(res.orderBandInterBillUppers[0].hasOwnProperty('priceRmb')){
            const result2= await CustOrderService.transferAmount({amount: res.orderBillUpperParts[0].priceRmb});
            this.Form.rmbBig.value = result2.meta.amount;
          };
        };
        if(res.hasOwnProperty('taskIds')) {
          for (var key in result.meta.taskIds) {
            this.taskId = result.meta.taskIds[key].taskId;
          }
        }else{
          this.taskId = 'TACHE00070002';
        }
        this.btnInit(result);
      }else{
        this.$message({
          showClose: true,
          message: res.resultMsg,
          type: 'error'
        });
      }
    },
    async save() {
      this.loading = true;
      let {custSoNumber, custId} = this.allInfo;
      let params = {
        custId: custId,
        custSoNumber: custSoNumber,
        userId: this.user.staffId,
        orgId: this.user.orgId,
        userName: this.user.staffName,
        orderAuditId: this.rowInfo.orderAuditId,
        acctItemLists: [{
          custId: custId,
          lastModifyBy: this.user.staffId,
          lastModifyDate: this.$util.dateFormat(new Date(), "yyyy-MM-dd hh:mm:ss"),
          actType: "MOD",
          billComment: this.FormB.billComment.value,
          acctItemListId: this.rowInfo.acctItemListId
        }],
      }
      const result = await CustOrderService.commonOrderUpdate(params);
      this.loading = false;
      if (result.meta.resultCode == 0) {
        this.$message({
          type: 'success',
          message: '保存成功!',
        });
        this.getDetail();
      } else {
        this.$message({
          showClose: true,
          message: result.meta.resultMsg,
          type: 'error',
        });
      }
    },
    // 修改优惠率
    async modidyRate() {
      this.loading = true;
      let {custOrderId, custSoNumber, orderAuditId, custId} = this.allInfo;
      // 再详情返回表格中取
      let acctItems = [];
      this.GQtbs.tableData.forEach((item,index)=>{
        acctItems.push({
          custId: custId,
          actType: "MOD",
          ratio: item.radioMat,
          acctItemTypeId:"2005000",
          orderItemId: item.orderItemId,
          acctTypeCd:item.acctTypeCd
        },{
              custId: custId,
              actType: "MOD",
              ratio: item.radioMat,
              acctItemTypeId:"2002000",
              orderItemId: item.orderItemId,
              acctTypeCd:item.acctTypeCd
            },{
          custId: custId,
          actType: "MOD",
          ratio: item.radioMat,
          acctItemTypeId:"2006000",
          orderItemId: item.orderItemId,
          acctTypeCd:item.acctTypeCd
        },{
          custId: custId,
          actType: "MOD",
          ratio: item.radioDev,
          acctItemTypeId:"2008000",
          orderItemId: item.orderItemId,
          acctTypeCd:item.acctTypeCd
        },{
          custId: custId,
          actType: "MOD",
          ratio: item.radioEng,
          acctItemTypeId:"2009000",
          orderItemId: item.orderItemId,
          acctTypeCd: item.acctTypeCd
        });
      });
      let params = {
        custId: custId,
        custSoNumber: custSoNumber,
        userId: this.user.staffId,
        orgId: this.user.orgId,
        userName: this.user.staffName,
        orderAuditId: orderAuditId,
        acctItems: acctItems
      }
      
      const result = await CustOrderService.commonOrderUpdate(params);
      this.loading = false;
      if (result.meta.resultCode == 0) {
        this.$message({
          type: 'success',
          message: '保存成功!',
        });
        this.getDetail();
      } else {
        this.$message({
          showClose: true,
          message: result.meta.resultMsg,
          type: 'error',
        });
      }
    },
    tableDataInit(arr){
      
      
      let le = {moneyRmbMat:"0",moneyRmbTest:"0",moneyRmbPro:"0",moneyRmbEng:"0",moneyRmbDev:"0"},
          le2 = {radioMat:'0',radioEng:'0',radioDev:'0'};
      let newarr = [];
      arr.map((item,index)=>{
        let les = {...le,...le2};
        Object.assign(les,item);
        item = {...les};
        item.subtotal = '￥'+(Number(item.moneyRmbMat)+Number(item.moneyRmbTest)+Number(item.moneyRmbPro));
        item.receivables = '￥'+(Number(item.moneyRmbMat)+Number(item.moneyRmbTest)+Number(item.moneyRmbPro)+Number(item.moneyRmbEng)+Number(item.moneyRmbDev));
        for(var key in item){
          if(le[key]){
            item[key] = '￥'+item[key];
          }
        }
        newarr.push(item);
      })
      return newarr;
    },
    closeFun(){
      this.$emit('update:show',false)
    },
    getLabel(opt,VALUE){
      for(var key in opt){
        let item = opt[key];
        if(item.value==VALUE){
          
          return item.label;
        }
      }
    },
    btnInit(res){
      // 临时
      let {audFlag,createBy,custManagerId,sendAudFlag} = res,
          userId = this.user.staffId,
          taskId = this.taskId;
      if(createBy==userId){
        if(taskId!=null && taskId.indexOf("TACHE00070002")!= -1 && (audFlag!=="1"||(sendAudFlag==1 && audFlag==2))){
          // 展示 送审核 ，重新报价 ，保存
          this.showBtn1 = true;
        }
      };
      if(custManagerId==userId){
        if(taskId!=null && taskId.indexOf("TACHE00070003") != -1 && sendAudFlag=="1" && audFlag!="1"){
          // 展示 确认 ，保存
          this.showBtn2 = true;
        }
      };
    },
  }
}
</script>

<style lang="scss" scoped>
.generate-bill-info{
  height: 84vh;
  padding-bottom: .3rem;
  .ne-line-r{
    &>div{
      margin-right: .1rem;
    }
  }
  .fixed{
    position: absolute;
    bottom: -.1rem;
    left: 0;
    right: 0;
    margin: 0 auto;
  }
}
</style>
